from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

def getDateList(urls):
  resp = urlopen(urls).read().decode('gbk')
  soup = BeautifulSoup(resp, 'html.parser')
  tds = soup.find_all("td", {"style":"text-align:center"})
  list1 = []
  for td in tds:
    if not td.find('font'):
      list1.append(td.get_text())

  dates = list1[:-1:2]
  dates.reverse()
  return dates[-39:]

def getMoneyList(urls):
  resp = urlopen(urls).read().decode('gbk')
  soup = BeautifulSoup(resp, 'html.parser')
  tds = soup.find_all("td", {"style":"text-align:center"})
  list1 = []
  for td in tds:
    if not td.find('font') and td.get_text() != ' ':
      list1.append(td.get_text())
  incom = []
  for index, name in enumerate(list1):
    if index % 2 != 0:
      incom.append(name)
  incom = list(reversed(incom))
  #print(incom)
  incomfloat = []
  str = ''
  for i in incom:
    str = i.replace(',','')
    incomfloat.append(float(str))
  return incomfloat[-39:]

def getDataSoup(urlStr):
  resp = urlopen(urlStr).read().decode('gbk')
  soup = BeautifulSoup(resp, 'html.parser')
  return soup.find_all("a", href = re.compile('/corp/'))



code = input('股票代码：')
url1 = 'http://money.finance.sina.com.cn/corp/go.php/vFD_ProfitStatement/stockid/'+ code +'/ctrl/2020/displaytype/4.phtml'
listUrls = getDataSoup(url1)
bizinco = ''
# 归属于母公司所有者的净利润
parenetp = ''
for url in listUrls:
  print(url.get_text(), '----', url["href"])
  if r'营业收入' == url.get_text():
    bizinco = "http://money.finance.sina.com.cn" + url["href"]
  if '五、净利润' == url.get_text():
    parenetp = "http://money.finance.sina.com.cn" + url["href"]
#bizinco = "http://money.finance.sina.com.cn" + '/corp/view/vFD_FinanceSummaryHistory.php?stockid=600410&type=BIZINCO&cate=liru5'
print(bizinco)
# print(getDateList(bizinco)) # 获取近10年报表
print(parenetp)
print(getMoneyList(bizinco))
print(getMoneyList(parenetp))

contents = []
with open('stock.html', 'r', encoding='utf-8') as f:
  while True:
    myStr = f.readline()
    if not myStr:
        break
    contents.append(myStr)

contents[11] = '      var date = ' + str(getDateList(bizinco)) + ';\r'
contents[12] = '      var businessIncome = ' + str(getMoneyList(bizinco)) + ';\r'
contents[13] = '      var netProfit = ' + str(getMoneyList(parenetp)) + ';\r'
contents[14] = '      var title = \'' + code + '\';\r'
# print(type(contents[11]),contents[11])
# print(type(contents[12]),contents[12])
# print(type(contents[13]),contents[13])
# print('=================================')
# print(''.join(contents))

with open('stock.html', 'w', encoding='utf-8') as f:
  f.writelines(contents)